<!--考勤打卡页面-->
<template>
  <div class="kaoqinContainer">
    <!--头部bar开始-->
    <CommonBar :options="options"></CommonBar>
    <!--头部bar结束-->
    <!--选择日期开始-->
    <div class="kaoqinTop">
      <!--考勤人开始-->
      <div class="kaoqinName">
        <van-image
          v-if="userphoto"
          round
          width="45px"
          height="45px"
          :src="`http://www.kdehw.com:83/uploads/images/user/${userphoto}`"
          fit="cover"
          class="kaoqintx"
        />
        <p class="txphoto" v-else>{{substringname(Info.name)}}</p>
        <div>
          <p class="name">{{Info.name}}</p>
          <p class="title">{{Info.group_name}}</p>
        </div>
      </div>
      <!--考勤人结束-->
    </div>
    <!--选择日期结束-->
    <!--考勤内容开始-->
    <div class="kaoqinContent">
      <!--步骤条开始-->
      <van-steps :active="stepactive" active-color="#15BC83" direction="vertical" class="vanStep">
        <!--上班时间开始-->
        <van-step>
          <p class="worktime">上班打卡</p>
          <div class="punchdiv">
            <!--未打卡开始-->
            <div v-if="shangbandakashow" class="textcenter">
              <button
                class="punchcontent"
                :class="workbut?'punchcontent1':''"
                @click="onworkClick"
                :disabled="workbut"
              >
                <div>
                  <p class="title">{{workdesc}}</p>
                  <p class="time">{{valtime}}</p>
                </div>
              </button>
              <p class="punchmap">
                <van-icon name="checked" :class="workbut?'checkedicon1':''" class="checkedicon" />
                <span>{{areadesc}}</span>
              </p>
            </div>
            <!--未打卡结束-->
            <!--上班已打卡开始-->
            <div v-else>
              <p class="dakatime">打卡时间{{onworktime}}</p>
              <p class="locationp">
                <van-icon name="location" class="location" />
                <span>{{office_address}}</span>
              </p>
              <p class="refreshp">
                <span @click="refreshOnwork">更新打卡</span>
                <van-icon name="arrow" class="arrowright" />
              </p>
            </div>
            <!--上班已打卡结束-->
          </div>
        </van-step>
        <!--上班时间结束-->
        <!--下班时间开始-->
        <van-step v-show="offworkDivShow">
          <p class="worktime">下班打卡</p>
          <div class="punchdiv">
            <!--未打卡开始-->
            <div v-if="xiabandakashow" class="textcenter">
              <button
                class="punchcontent"
                :class="offworkbut?'punchcontent1':''"
                @click="offworkClick"
                :disabled="offworkbut"
              >
                <div>
                  <p class="title">{{offworkdesc}}</p>
                  <p class="time">{{valtime}}</p>
                </div>
              </button>
              <p class="punchmap">
                <van-icon name="checked" class="checkedicon" :class="offworkbut?'checkedicon1':''" />
                <span>{{areadesc}}</span>
              </p>
            </div>
            <!--未打卡结束-->
            <!--下班已打卡开始-->
            <div v-else>
              <p class="dakatime">打卡时间{{offworktime}}</p>
              <p class="locationp">
                <van-icon name="location" class="location" />
                <span>{{office_address}}</span>
              </p>
              <p class="refreshp">
                <span @click="refreshOffwork">更新打卡</span>
                <van-icon name="arrow" class="arrowright" />
              </p>
            </div>
            <!--下班已打卡结束-->
          </div>
        </van-step>
        <!--下班时间结束-->
      </van-steps>
      <!--步骤条结束-->
    </div>
    <!--考勤内容结束-->
    <!--办公室考勤开始位置-->
    <div id="area"></div>
    <!--办公室考勤结束位置-->
  </div>
</template>
<script>
import BMap from "BMap";
import CommonBar from "../common/commonBar";
import { mapState } from "vuex";
export default {
  components: {
    CommonBar
  },
  computed: {
    ...mapState({
      token: state => state.Authorization
    })
  },
  data() {
    return {
      options: {
        type: "icon",
        centerText: "考勤打卡",
        iconNname: "wap-home",
        lefttype: "left"
      },
      stepactive: 0,
      offworkDivShow: false, //整个下班流程是否显示
      shangbandakashow: true, //上班打卡的两步
      xiabandakashow: true, //下班打卡的两步
      //年月日
      showPickerdate: false,
      signdate: "", //出生日期
      currentDate: new Date(),
      minDate: new Date(1900, 1, 1),
      maxDate: new Date(),
      valtime: "", //系统时间
      pathlocation: "",
      creditLongitude: "", //当前经度
      creditLatitude: "", //当前纬度
      creditAddress: "", //当前位置
      Info: {}, //考勤信息
      userphoto: "", //头像
      areadesc: "未进入考勤范围", //范围描述
      offworkdesc: "下班打卡", //下班描述
      workdesc: "上班打卡", //上班描述
      onworktime: "", //打卡描述
      offworktime: "", //下班时间
      office_address: "", //办公地点
      effective_range: "", //考勤地点范围
      office_lng: "", //办公经度
      office_lat: "", //办公维度
      rule_type: "", //考勤类型，1是办公室，2是责任区域
      duty_area: [], //责任区域坐标
      workbut: true, //上班打卡按钮
      offworkbut: "",
      bmap: null,
      translateCallback: ""
    };
  },

  methods: {
    //取头像
      substringname(username) {
      if (username) {
        if (username.length >= 3) {
          return username.substr(username.length - 2, 2);
        } else {
          return username;
        }
      }
    },
    //考勤信息
    getloadData(params) {
      this.$http
        .get(`${this.$basePath}?service=App.Attendance.InfoCheckIn&api=88`, {
          params: params
        })
        .then(res => {
          if (res.ret == 200) {
            console.log("考勤信息", res);
            this.effective_range = res.data.effective_range;
            this.rule_type = res.data.rule_type;
            this.Info = res.data;
            this.office_address = res.data.office_address;
            this.userphoto = res.data.photo;

            this.duty_area = eval(res.data.duty_area);
            console.log("责任区域坐标", this.duty_area);
            //将json字符串转化为json对象
            var ret = res.data.office_location;
            if (ret && typeof ret == "string") {
              var obj = JSON.parse(ret);
              console.log("obj", obj.lng, obj.lat);
              this.office_lng = obj.lng;
              this.office_lat = obj.lat;
              console.log("办公室坐标", this.office_lng, this.office_lat);
            }

            this.$nextTick(() => {
              this.getposition();
            });
            //给打卡时间赋值
            var sign_record = res.data.sign_record;
            if (sign_record.length == 1) {
              this.offworkDivShow = true;
              this.shangbandakashow = false;
              this.xiabandakashow = true;
            } else if (sign_record.length == 2) {
              this.offworkDivShow = true;
              this.shangbandakashow = false;
              this.xiabandakashow = false;
            } else if (sign_record.length == 0) {
              this.shangbandakashow = true;
              this.xiabandakashow = true;
              this.offworkDivShow = false;
            }
            //更新打卡
            if (sign_record[0].update_date != null) {
              this.onworktime = sign_record[0].update_date.split(" ")[1];
            } else {
              this.onworktime = sign_record[0].create_date.split(" ")[1];
            }
            if (sign_record[1].update_date != null) {
              this.offworktime = sign_record[1].update_date.split(" ")[1];
            } else {
              this.offworktime = sign_record[1].create_date.split(" ")[1];
            }
          } else if (res.ret == 101) {
            this.$toast({ message: res.msg });
            this.workbut = true;
            this.Info = res.data;
            this.userphoto = res.data.photo;
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    //更新上班打卡
    refreshOnwork() {
      this.shangbandakashow = true;
    },
    //点击上班打卡事件
    onworkClick() {
      this.offworkDivShow = true;
      this.shangbandakashow = !this.shangbandakashow;
      this.stepactive = 1;

      this.params = {
        token: this.token,
        type: 1,
        workplace: { lon: this.creditLatitude, lat: this.creditLongitude }
      };
      this.$http
        .get(`${this.$basePath}?service=App.Attendance.CheckIn&api=88`, {
          params: this.params
        })
        .then(res => {
          if (res.ret == 200) {
            this.$toast({ message: res.msg });
            //再次获取信息
            var params = { token: this.token };
            this.getloadData(params);
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    //更新下班打卡
    refreshOffwork() {
      this.xiabandakashow = true;
    },
    //点击下班打卡事件
    offworkClick() {
      this.xiabandakashow = !this.xiabandakashow;
      this.stepactive = 2;

      this.params = {
        token: this.token,
        type: 2,
        workplace: { lon: this.creditLatitude, lat: this.creditLongitude }
      };
      this.$http
        .get(`${this.$basePath}?service=App.Attendance.CheckIn&api=88`, {
          params: this.params
        })
        .then(res => {
          if (res.ret == 200) {
            this.$toast({ message: res.msg });
            //再次获取信息

            var params = { token: this.token };
            this.getloadData(params);
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    //日期选中
    onConfirmdate(val) {
      var d = new Date(val);
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      var datetime = year + "-" + month + "-" + day;
      this.signdate = datetime;
      this.showPickerdate = false;

      var params = { token: this.token, date: this.signdate };
      this.getloadData(params);
    },
    //日期格式化
    formatterDate(type, val) {
      if (type === "year") {
        return `${val}年`;
      } else if (type === "month") {
        return `${val}月`;
      } else if (type === "day") {
        return `${val}日`;
      }
      return val;
    },

    //系统时间
    showTime: function() {
      let d = new Date();

      let hour = d.getHours();
      let minute = d.getMinutes();
      let seconds = d.getSeconds();

      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      if (seconds >= 0 && seconds <= 9) {
        seconds = `0${seconds}`;
      }
      this.valtime = hour + ":" + minute + ":" + seconds;
    },
    //系统日期
    showDate() {
      var d = new Date();
      let year = d.getFullYear();
      let month = d.getMonth() + 1;
      let day = d.getDate();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      this.signdate = year + "-" + month + "-" + day;
    },
    //获取坐标
    getposition() {
      var that = this;
      console.log(111);
      navigator.geolocation.getCurrentPosition(
        function(position) {
          var currentLat = position.coords.latitude;
          var currentLng = position.coords.longitude;
          console.log("经度", currentLng, "纬度", currentLat);
          that.initBmap(currentLng, currentLat);
        },
        function(error) {
          console.log(error.message, "温馨提示");
        }
      );
    },
    //判断区域
    initBmap(Lng, Lat) {
      var that = this;
      that.bmap = new BMap.Map("area", { drawer: BMAP_SVG_DRAWER });
      that.bmap.enableScrollWheelZoom(); // 开启鼠标滚轮缩放
      that.bmap.addControl(new BMap.ScaleControl()); // 添加比例尺控件
      //标位置点
      if (Lng || Lat) {
        var point1 = new BMap.Point(Lng, Lat);
        var markergg1 = new BMap.Marker(point1);
        that.bmap.addOverlay(markergg1); //添加GPS marker
        var labelgg1 = new BMap.Label("原始坐标", {
          offset: new BMap.Size(20, -10)
        });
        //转换坐标
        that.translateCallback = function(data) {
          console.log(111111);
          if (data.status === 0) {
            console.log("转换后的百度坐标", data.points[0]);
            var translng = data.points[0].lng;
            var translat = data.points[0].lat;
            var marker = new BMap.Marker(data.points[0]);
            that.bmap.addOverlay(marker);
            var label = new BMap.Label("转换后的百度坐标（正确）", {
              offset: new BMap.Size(20, -10)
            });
            marker.setLabel(label); //添加百度label
            that.bmap.setCenter(data.points[0]);

            //判断是办公室
            if (that.rule_type == 1) {
              //创建办公室地址

              var point = new BMap.Point(that.office_lng, that.office_lat);
              //var point = new BMap.Point(112.892668, 28.214665);
              that.bmap.centerAndZoom(point, 15);
              that.bmap.addOverlay(new BMap.Marker(point));
              that.bmap.enableScrollWheelZoom(); // 开启鼠标滚轮缩放
              that.bmap.addControl(new BMap.ScaleControl()); // 添加比例尺控件
              var r = that.effective_range / 2;
              // 创建以点为中心的圆
              var circle = new BMap.Circle(point, r, {
                strokeColor: "red", //线颜色
                strokeWeight: 2, //线宽
                fillColor: "#f18900", // 填充色
                fillOpacity: "0.1" // 填充透明度
              });
              that.bmap.addOverlay(circle);
              //比较当前位置是否在区域内
              var msg = "";
              var pt = new BMap.Point(translng, translat); //这是当前坐标
              //http://api.that.bmap.baidu.com/ag/coord/convert?from=0&to=4&x=112.97935279&y=28.21347823
              //  var pt = new BMap.Point(112.97935279, 28.21347823); //这是当前坐标
              that.bmap.addOverlay(new BMap.Marker(pt));
              if (BMapLib.GeoUtils.isPointInPolygon(pt, circle)) {
                console.log("已进入");
                //如果点在区域内，返回true
                //that.$toast({ message: "已进入办公室范围" });
                that.bmap.addOverlay(new BMap.Marker(pt));
                that.areadesc = "已进入考勤范围";

                that.workbut = false;
                that.offworkbut = false;
              } else {
                console.log("未进入");
                //that.$toast({ message: "未进入办公室范围" });
                that.bmap.addOverlay(new BMap.Marker(pt));
                that.areadesc = "未进入考勤范围";

                that.workbut = true;
                that.offworkbut = true;
              }
            } else if (that.rule_type == 2) {
              //责任区范围
              if (that.duty_area == null) {
              }
              var point = new BMap.Point(112.934855, 28.22836);
              that.bmap.centerAndZoom(point, 15);
              that.bmap.enableScrollWheelZoom(); // 开启鼠标滚轮缩放
              that.bmap.addControl(new BMap.ScaleControl()); // 添加比例尺控件
              // 生成坐标点
              var trackPoint = [];
              if (that.duty_area != null) {
                for (var i = 0, j = that.duty_area.length; i < j; i++) {
                  trackPoint.push(
                    new BMap.Point(that.duty_area[i].lng, that.duty_area[i].lat)
                  );
                }
                that.bmap.centerAndZoom(trackPoint[0], 15);
              } else {
                that.$toast({ message: "未划分责任区" });
                that.workbut = true;
                that.offworkbut = true;
                return;
              }

              // 画区域
              var polyline = new BMap.Polygon(trackPoint, {
                strokeColor: "red",
                strokeWeight: 3,
                strokeOpacity: 1
              });
              that.bmap.addOverlay(polyline);
              //判断当前坐标是否在区域内
              var msg = "";
              var pt = new BMap.Point(translng, translat); //这是当前坐标
              //  var pt = new BMap.Point(112.956864, 28.169968); //这是当前坐标

              that.bmap.addOverlay(new BMap.Marker(pt));
              if (BMapLib.GeoUtils.isPointInPolygon(pt, polyline)) {
                //如果点在区域内，返回true
                //that.$toast({ message: "已进入责任范围" });
                that.bmap.addOverlay(new BMap.Marker(pt));
                that.areadesc = "已进入考勤范围";

                that.workbut = false;
                that.offworkbut = false;
              } else {
                that.bmap.addOverlay(new BMap.Marker(pt));
                //that.$toast({ message: "未进入责任范围" });
                that.areadesc = "未进入考勤范围";

                that.workbut = true;
                that.offworkbut = true;
              }
            }
          }
        };
        var convertor = new BMap.Convertor();
        var pointArr = [];
        pointArr.push(point1);
        convertor.translate(pointArr, 1, 5, that.translateCallback);
      } else {
        that.$toast({ message: "无法获取坐标" });
      }
    }
  },
  mounted() {
    var params = { token: this.token };
    this.getloadData(params);
  },
  created() {
    //初始化日期
    this.showDate();
    setInterval(this.showTime, 0);
  }
};
</script>
<style lang="less" scoped>
#area {
  // width: 100%;
  // height: 500px;
}
@import "../../assets/css/attendence";
[class*="van-hairline"]::after {
  border: none;
}
.van-steps--vertical {
  box-sizing: border-box;
}
.checkedicon1 {
  color: #999 !important;
}
</style>